package com.mrd.serverconnect.pkg;

import android.content.Context;
import android.util.Log;

import com.mrd.serverconnect.util.SPUtils;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

/**
 * Created by liushenen on 2018/1/31.
 */

public class UpPKGHelp extends PKGBase {
    private static final String TAG = "UpPKGHelp";
    private long lastRecordTime;
    private Context context;
    private final String lastRecordTimeKey = "lastRecordTime";

    public UpPKGHelp(Context context){
        this.context = context;
        lastRecordTime = SPUtils.getLong(context,lastRecordTimeKey,0);
    }

    public UpReqData readReqData(byte[] head, byte funCode, DataInputStream dataInputStream) {
        //获取当前时间戳
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        long now = System.currentTimeMillis();
        UpReqData mUpReqData = new UpReqData();
        mUpReqData.head = head;
        mUpReqData.funCode = funCode;
        long maxTime = -1;
        try {
            mUpReqData.num = dataInputStream.readShort();
            byte[] numData = readReqData(mUpReqData.num * 40, dataInputStream);
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(numData);
            DataInputStream itemDataIn = new DataInputStream(byteArrayInputStream);
            mUpReqData.numData = numData;
            mUpReqData.mPassengerItem = new ArrayList<>();
            for (int i = 0; i < mUpReqData.num; i++) {
                PassengerItem passengerItem = new PassengerItem();
                byte[] sn = new byte[16];
                byte[] time = new byte[20];

                itemDataIn.read(sn);
                passengerItem.in = itemDataIn.readShort();

                passengerItem.out = itemDataIn.readShort();
                itemDataIn.read(time);
                passengerItem.sn = new String(sn, 0, getVirtualValueLength(sn), "utf-8");
                passengerItem.time = new String(time, 0, getVirtualValueLength(time), "utf-8");
                long itemDataTimeStamp;
                try {
                    itemDataTimeStamp = dateToStamp(passengerItem.time);
                } catch (ParseException e) {
                    Log.e(TAG, "日期解析失败", e);
                    continue;
                }

                boolean morethan5min = Math.abs(now - itemDataTimeStamp) < 5 * 60 * 1000;//5分钟以内
                boolean moreThanLast = itemDataTimeStamp > lastRecordTime;// 比上一次时间大

                Log.i(TAG, "readReqData: lastCordTime:" + formatter.format(new Date(lastRecordTime))
                        + "itemDataTimeStamp:" + formatter.format(new Date(itemDataTimeStamp ))  + "now:" + formatter.format(new Date(now)) );

                if (morethan5min && moreThanLast) {
                    mUpReqData.mPassengerItem.add(passengerItem);
                    maxTime = Math.max(maxTime, itemDataTimeStamp);
                } else {
//                    Log.i(TAG, "不满足条件的时候readReqData: lastCordTime:" + formatter.format(new Date(lastRecordTime))
//                            + "itemDataTimeStamp:" + formatter.format(new Date(itemDataTimeStamp ))  + "now:" + formatter.format(new Date(now)) );

                    Log.i(TAG, "不满足条件的数据是：" + passengerItem.toString());
                }
            }
        } catch (IOException e) {
            Log.e(TAG, "modbus read data IOException： " + e.getMessage());
        }
        if (maxTime != -1) {
            lastRecordTime = maxTime;
            SPUtils.putLong(context,lastRecordTimeKey,lastRecordTime);
        }
        return mUpReqData;
    }

    /*
     * 将时间转换为时间戳
     */
    private long dateToStamp(String time) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        simpleDateFormat.setTimeZone(TimeZone.getDefault());
        Date date = simpleDateFormat.parse(time);
        long ts = date.getTime();
        return ts;
    }

    public static long timeStr2Long(String datestr) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.CHINA);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+08"));
        Date date = null;
        try {
            date = dateFormat.parse(datestr);
        } catch (ParseException e) {
            Log.e("timeStr2Long", e.getMessage());
        }
        if (date == null) {
            return 0;
        }
        return date.getTime();
    }

    /*
     * 将时间戳转换为时间
     */
    private String stampToDate(long timeMillis) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(timeMillis);
        return simpleDateFormat.format(date);
    }

    public void sendData(byte[] head, OutputStream outputStream) {
        try {
            head[5] = 0x3;
            outputStream.write(head);
            outputStream.write(0x42);
            outputStream.write(0x00);
            outputStream.flush();
            //Log.d(TAG, "接收上传数据成功回应=================");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取字符串字节流中有效字节个数
     *
     * @param buf
     * @return
     */
    public static int getVirtualValueLength(byte[] buf) {
        int i = 0;
        for (; i < buf.length; i++) {
            if (buf[i] == (byte) 0) {
                break;
            }
        }
        return i;

    }

    /**
     * 读取数据
     *
     * @param len
     * @param dataInputStream
     * @return
     * @throws IOException
     */
    public byte[] readReqData(int len, DataInputStream dataInputStream) throws IOException {
        byte[] data = new byte[len];
        byte[] temp = new byte[1];
        for (int i = 0; i < len; i++) {
            dataInputStream.read(temp);
            data[i] = temp[0];
        }
        return data;
    }


    public class UpReqData extends BaseReqData {
        short num;//客流条数
        byte[] numData;//客流数据
        List<PassengerItem> mPassengerItem;//客流人数

        public short getNum() {
            return num;
        }

        public void setNum(short num) {
            this.num = num;
        }

        public byte[] getNumData() {
            return numData;
        }

        public void setNumData(byte[] numData) {
            this.numData = numData;
        }

        public List<PassengerItem> getmPassengerItem() {
            return mPassengerItem;
        }

        public void setmPassengerItem(List<PassengerItem> mPassengerItem) {
            this.mPassengerItem = mPassengerItem;
        }
    }

    public static class PassengerItem {
        String sn;
        Short in;
        Short out;
        String time;

        public PassengerItem() {

        }

        public PassengerItem(String sn, Short in, Short out, String time) {
            this.sn = sn;
            this.in = in;
            this.out = out;
            this.time = time;
        }

        public String getSn() {
            return sn;
        }

        public void setSn(String sn) {
            this.sn = sn;
        }

        public Short getIn() {
            return in;
        }

        public void setIn(Short in) {
            this.in = in;
        }

        public Short getOut() {
            return out;
        }

        public void setOut(Short out) {
            this.out = out;
        }

        public String getTime() {
            return time;
        }

        public void setTime(String time) {
            this.time = time;
        }

        @Override
        public String toString() {
            return "PassengerItem{" +
                    "sn='" + sn + '\'' +
                    ", in=" + in +
                    ", out=" + out +
                    ", time='" + time + '\'' +
                    '}';
        }
    }

    public static class Passenger {
        Short in;
        String time;

        public Short getIn() {
            return in;
        }

        public void setIn(Short in) {
            this.in = in;
        }

        public String getTime() {
            return time;
        }

        public void setTime(String time) {
            this.time = time;
        }

        public Passenger(Short in, String time) {
            this.in = in;
            this.time = time;
        }
    }
}
